package com.wenwei.paper.net;



import com.orhanobut.logger.Logger;
import com.wenwei.paper.base.BaseApplication;
import com.wenwei.paper.base.Constant;
import com.wenwei.paper.bean.AddGoodsListBean;
import com.wenwei.paper.bean.ApiResultBean;
import com.wenwei.paper.bean.DeviceListBean;
import com.wenwei.paper.bean.MessageBean;
import com.wenwei.paper.bean.PageBean;
import com.wenwei.paper.bean.ReplenishmentDetailBean;
import com.wenwei.paper.bean.ReplenishmentEndListBean;
import com.wenwei.paper.bean.ReplenishmentListBean;
import com.wenwei.paper.bean.UserLoginBean;
import com.wenwei.paper.bean.VersionBean;
import com.wenwei.paper.utils.UserStringUtils;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.functions.Func1;

/**
 *
 *
  * 对Retrofit 请求过程进行封装
 */
public class ApiManager {
    public static final int DEFAULT_TIMEOUT = 10;//设置默认超时时间
    private Retrofit retrofit ;
    private ApiInterface mApiService;
    /**
     * 构造方法私有
     */
    private ApiManager(){
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClientBuilder.addNetworkInterceptor(new LogInterceptor());
        final String s = UserStringUtils.getUserToken(BaseApplication.getAppContext());
        Logger.d("headerToken:"+s);
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("ww-token", UserStringUtils.getUserToken(BaseApplication.getAppContext()))
                        .build();
                return chain.proceed(request);
            }
        });
        //Retrofit的一些配置
        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())//配置okHttp
                .addConverterFactory(GsonConverterFactory.create())//配置CallModel可以使用Gson直接创建Bean
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//配置ApiService请求可以使用RxJava
                .baseUrl(Constant.BASE_URL)//配置服务器地址
                .build();//创建

        mApiService = retrofit.create(ApiInterface.class);//创建API请求接口
    }

    private static class SingletonHolder{
        private static final ApiManager INSTANCE = new ApiManager();
    }

    public static ApiManager getInstance(){
        return SingletonHolder.INSTANCE;
    }


    private class HttpResultFunc<T> implements Func1<ApiResultBean<T>, T> {
        @Override
        public T call(ApiResultBean<T> httpResult) {
            if (httpResult.getCode()!=200) {
                throw new ApiException(httpResult.getMsg());
            }
            return httpResult.getData();
        }
    }

    //获取短信验证码
    public void getSmsCode(BaseSubscriber subscriber,String phone,int type){
        mApiService.getSmsCode(phone,type).map(new HttpResultFunc<ArrayList>())
                .compose(TransformUtils.<ArrayList>defaultSchedulers())
                .subscribe(subscriber);
    }

    //注册
    public void userRegister(BaseSubscriber subscriber,String bodyStr){
        mApiService.userRegister(getBody(bodyStr))
                .map(new HttpResultFunc<ArrayList>())
                .compose(TransformUtils.<ArrayList>defaultSchedulers())
                .subscribe(subscriber);
    }

    //登录
    public void userLogin(BaseSubscriber subscriber,String phone,String ps,String id){
        mApiService.userLogin(phone,ps,id)
                .map(new HttpResultFunc<UserLoginBean>())
                .compose(TransformUtils.<UserLoginBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //忘记密码
    public void userUpdate(BaseSubscriber subscriber,String s){
        mApiService.userUpdate(getBody(s))
                .map(new HttpResultFunc<UserLoginBean>())
                .compose(TransformUtils.<UserLoginBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //消息通知
    public void MessageNotify(BaseSubscriber subscriber){
        mApiService.messageNotify()
                .map(new HttpResultFunc<MessageBean>())
                .compose(TransformUtils.<MessageBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    //补货通知列表
    public void getReplenishmentList(BaseSubscriber subscriber,int page){
        mApiService.getReplenishmentList(page)
                .map(new HttpResultFunc<PageBean<ArrayList<ReplenishmentListBean>>>())
                .compose(TransformUtils.<PageBean<ArrayList<ReplenishmentListBean>>>defaultSchedulers())
                .subscribe(subscriber);
    }

    //补货详情
    public void getReplenishmentDetails(BaseSubscriber sub,int id){
        mApiService.getReplenishmentDetails(id)
                .map(new HttpResultFunc<ReplenishmentDetailBean>())
                .compose(TransformUtils.<ReplenishmentDetailBean>defaultSchedulers())
                .subscribe(sub);
    }

    //已补货列表
    public void getReplenishmentEnd(BaseSubscriber subscriber,int page){
        mApiService.getReplenishmentEnd(page)
                .map(new HttpResultFunc<PageBean<ArrayList<ReplenishmentEndListBean>>>())
                .compose(TransformUtils.<PageBean<ArrayList<ReplenishmentEndListBean>>>defaultSchedulers())
                .subscribe(subscriber);
    }


    //配货商品列表
    public void getAddGoodsList(BaseSubscriber subscriber,String deviceId){
        mApiService.getAddGoodsList(deviceId)
                .map(new HttpResultFunc<ArrayList<AddGoodsListBean>>())
                .compose(TransformUtils.<ArrayList<AddGoodsListBean>>defaultSchedulers())
                .subscribe(subscriber);
    }



    //设备列表
    public void getDeviceList(BaseSubscriber subscriber,int page){
        mApiService.getDeviceList(page)
                .map(new HttpResultFunc<PageBean<ArrayList<DeviceListBean>>>())
                .compose(TransformUtils.<PageBean<ArrayList<DeviceListBean>>>defaultSchedulers())
                .subscribe(subscriber);
    }

    //版本号
    public void getVersion(BaseSubscriber subscriber,int code ){
        mApiService.getVersion(1,code)
                .map(new HttpResultFunc<VersionBean>())
                .compose(TransformUtils.<VersionBean>defaultSchedulers())
                .subscribe(subscriber);
    }

    private RequestBody getBody(String s){
        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"),s);
    }

}
